package com.agileai.portal.bizmoduler.lang;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.bizmoduler.core.StandardServiceImpl;
import com.agileai.hotweb.i18n.BundleContext;
import com.agileai.hotweb.i18n.ResourceBundle;
import com.agileai.portal.driver.service.LocaleManager;
import com.agileai.util.StringUtil;

public class SysMultiLangManageImpl
        extends StandardServiceImpl
        implements SysMultiLangManage,LocaleManager {
	
	private static HashMap<String,List<DataRow>> LocaleMapCache = new HashMap<String,List<DataRow>>();
	
    public SysMultiLangManageImpl() {
        super();
    }

	@Override
	public void saveLangConf(String resourceType,DataParam param, List<DataParam> insertRecords, List<DataParam> updateRecords) {
		if (insertRecords != null && insertRecords.size() > 0){
			for (int i=0;i < insertRecords.size();i++){
				DataParam paramRow = insertRecords.get(i);
				processDataType(paramRow, tableName);	
				processPrimaryKeys(paramRow);
			}
		}
		String statementId = sqlNameSpace+"."+"insertRecord";
		this.daoHelper.batchInsert(statementId, insertRecords);
		
		statementId = sqlNameSpace+"."+"updateRecord";
		this.daoHelper.batchUpdate(statementId, updateRecords);

		if ((insertRecords != null && insertRecords.size() > 0)
				|| (updateRecords != null && updateRecords.size() > 0)){
			LocaleMapCache.remove(resourceType);
		}
	}

	@Override
	public HashMap<String, String> getLocaleMap(HttpServletRequest request,
			String resourceType) {
		HashMap<String,String> localeMap = new HashMap<String,String>();
		List<DataRow> records = null;
		if (LocaleMapCache.containsKey(resourceType)){
			records = LocaleMapCache.get(resourceType);
		}else{
			String statementId = sqlNameSpace+"."+"findRecords";
			DataParam param = new DataParam("resourceType",resourceType);
			records = this.daoHelper.queryRecords(statementId, param);
			LocaleMapCache.put(resourceType, records);
		}
		
		ResourceBundle bundle = BundleContext.getOnly().getResourceBundle(); 
		String locale = bundle.retrieveLocale(request);
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String resouceId = row.getString("MULTI_LANG_RESOURCE_ID");
				String localeLang = row.getString("MULTI_LANG_CODE");
				if (locale.equals(localeLang)){
					String localeText = row.getString("MULTI_LANG_VALUE");
					if (!StringUtil.isNullOrEmpty(localeText)){
						localeMap.put(resouceId, localeText);					
					}					
				}
			}
		}
		return localeMap;
	}
}
